package com.vjwealth.android.nos.utils

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.vjwealth.android.nos.entity.CustomerInforData
import com.vjwealth.android.nos.entity.CustomerInforEntity
import com.vjwealth.android.nos.entity.HomeCarData
import com.vjwealth.android.nos.entity.HomeCarEntity

/**
 * projectName KNOS
 * date 2017/9/26
 * description com.vjwealth.android.nos.utils
 */
class SPUtils(context: Context, spName: String){

    companion object {
        private val INIT_DATA = "initData"
        private val MY_CAR_LIST = "my_car_list"
    }

    private var sp: SharedPreferences? = null
    private var editor: SharedPreferences.Editor
    private var carList: List<HomeCarEntity>
    private var mInitData: CustomerInforEntity? = null

    init {
        sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        editor = sp!!.edit()
        editor.apply()
        carList = listOf()
    }
    fun getString(key: String, default: String = ""): String {
        return sp!!.getString(key, default)
    }

    fun putString(key: String, value: String){
        editor.putString(key, value).apply()
    }

    fun getInitDataByShared(): CustomerInforData {
        var jsonStr = getString(INIT_DATA)
        return Gson().fromJson(jsonStr, CustomerInforData::class.java)
    }

    fun putInitDataByShared(bean: CustomerInforData){
        var jsonStr = Gson().toJson(bean, CustomerInforData::class.java)
        editor.putString(INIT_DATA, jsonStr).apply()
    }

    fun getHomeCarList(): List<HomeCarData>{
        var jsonStr = getString(MY_CAR_LIST)
        return Gson().fromJson<List<HomeCarData>>(jsonStr, object : TypeToken<List<HomeCarData>>() {}.type)
    }

    fun putHomeCarList(myCarList: List<HomeCarData>){
        var jsonStr = Gson().toJson(myCarList)
        editor.putString(MY_CAR_LIST, jsonStr).apply()
    }

    fun clear(){
        editor.clear().apply()
    }
}